import { doPhoneTranslate } from 'admin/servers/modules/PhoneTranslate';
import { Button, Col, Form, Input, Row } from 'antd';
import TextArea from 'antd/lib/input/TextArea';
import React, { Component } from 'react';

import './style.scss';

interface Props {}
interface State {
  srcData: string;
  key: string;
  destData: string;
}

export default class PhoneTranslate extends Component<Props, State> {
  state = {
    srcData: '',
    key: '',
    destData: '',
    maxNum: 10000,
  };

  onFinish = async (values: any) => {
    console.log('Success:', values);
    const { srcData, key } = values;
    // srcData需要转换为逗号拼接，作为参数给后端
    // console.log('输入****号码ID:', srcData);
    const re = /\n/g;
    const newStr = srcData.replace(re, ',');
    // console.log('入参****号码ID:', newstr);
    try {
      const param = {
        srcData: newStr,
        key,
      };
      const { data } = await doPhoneTranslate(param);
      const str = data.destData.split(',').join('\n');
      this.setState({
        destData: str,
      });
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
  };

  onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };
  /**验证号码ID个数，用英文逗号或者换行分隔 */
  checkPhoneData = (str: string): boolean => {
    const re = /\n/g;
    const newStr = str.replace(re, ',');
    const arr = newStr.split(',');
    return arr.length <= this.state.maxNum ? true : false;
  };

  render() {
    const { destData, maxNum } = this.state;
    return (
      <div className="phone-translate">
        <Form
          labelCol={{ span: 2 }}
          wrapperCol={{ span: 20 }}
          onFinish={this.onFinish}
          onFinishFailed={this.onFinishFailed}
          autoComplete="off"
        >
          <Form.Item
            label="号码ID"
            name="srcData"
            rules={[
              { required: true, message: '请输入号码ID' },
              {
                validator: (_: any, value: string) => {
                  return this.checkPhoneData(value)
                    ? Promise.resolve()
                    : Promise.reject(`最多输入${maxNum}个号码ID`);
                },
              },
            ]}
            getValueFromEvent={event => {
              // 只能输入字母、数字和"+" "=" "/" "," "\n"
              return event.target.value.replace(/[^a-zA-Z0-9+=\/,\n]+/g, '');
            }}
          >
            <TextArea rows={8} placeholder={`最多支持输入${maxNum}个，多个用英文逗号分隔`} />
          </Form.Item>
          <Row>
            <Col span={8}>
              <Form.Item
                labelCol={{ span: 6 }}
                wrapperCol={{ span: 17 }}
                label="密钥"
                name="key"
                rules={[{ required: true, message: '请输入密钥' }]}
              >
                <Input maxLength={16} placeholder="请输入密钥" />
              </Form.Item>
            </Col>
            <Col span={4}>
              <Button type="primary" htmlType="submit">
                解密
              </Button>
            </Col>
          </Row>
          <Form.Item label="结果">
            <TextArea value={destData} rows={8} readOnly />
          </Form.Item>
        </Form>
      </div>
    );
  }
}
